package com.monkey4flux.datasource.demo;

import com.monkey4flux.datasource.demo.model.Person;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import lombok.extern.log4j.Log4j2;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import reactor.test.StepVerifier;

@Log4j2
public class R2dbcApp {

    public static void main(String[] args) throws InterruptedException {

        ConnectionFactory connectionFactory = ConnectionFactories.get("r2dbc:h2:mem:///test?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");

        R2dbcEntityTemplate template = new R2dbcEntityTemplate(connectionFactory);

        template.getDatabaseClient().sql("CREATE TABLE person" +
                        "(id VARCHAR(255) PRIMARY KEY," +
                        "name VARCHAR(255)," +
                        "age INT)")
                .fetch()
                .rowsUpdated()
                .as(StepVerifier::create)
                .expectNextCount(1)
                .verifyComplete();

        for (int i = 0; i < 100; i++) {
            template.insert(Person.class)
                    .using(new Person("joe" + i, "Joe" + i, 34 + i))
                    .as(StepVerifier::create)
                    .expectNextCount(1)
                    .verifyComplete();
        }

        template.select(Person.class)
                .all().subscribe(System.out::println);
//        block
//                .doOnNext(log::info)
//                .as(StepVerifier::create)
//                .expectNextCount(1)
//                .verifyComplete();

        Thread.sleep(10000);
    }
}
